<template>
	<views class="out-box">
		<!-- 布局 -->
		<audio class="player_box" :src="require('../assets/musics/music.mp3')" controls ref="myAudio"></audio>
		<!-- <audio class="player_box" :src="music" controls></audio> -->
		<div class="lrc_box" ref="lrcBox">
			<ul class="lrc_list" ref="lrcList">
				<!-- 乱数假文 >lorem10 -->
				<li class="lrc_word" v-for="val,index in lrcArr" :key="index">{{val.word}}</li>
			</ul>
		</div>
	</views>
</template>

<script>
	import lrc from "@/common/data.js"
	// import music from "@/assets/musics/music.mp3"
	export default {
		data() {
			return {
				lrc,
				lrcArr:[],
				domInfo:{},
				ulStyle:{
					transform:`translateY(0px)`
				}
				
			}
		},
		mounted() {
			this.parseLrc()
			this.setUlOffset()
		},
		methods: {
			/**
			 * 格式化歌词，格式化对象结果为：{time:'时间',word:'歌词'}
			 */
			parseLrc() {
				const lrcLines = this.lrc.split('\n')
				lrcLines.forEach(str => {
					const parts = str.split(']')
					const lrcObj = {
						time: this.parseTime(parts[0].substring(1)),
						word: parts[1]
					}
					this.lrcArr.push(lrcObj)
				})
			},
			/**
			 * 格式化时间
			 * @param {string} timeStr
			 * @returns {number} newTime
			 */
			parseTime(timeStr) {
				const parts = timeStr.split(':')
				return (parts[0] * 60 + (+parts[1])).toFixed(2)
			},
			/**
			 * 添加歌词滚动效果
			 */
			
			setUlOffset(){
				this.showLrc()
				let height = this.domInfo.liHeight*this.currentIndex+this.domInfo.liHeight/2 - this.domInfo.lrcBoxHeight/2
				if(height < 0){
					height = 0
				}
				this.ulStyle.transform = `translateY(-${height}px)`
			},
			showLrc(){
				this.findCurrentIndex()
				const oldLi = this.$refs.lrcList.querySelector('.lrc_word_active')
				oldLi?oldLi.classList.remove('lrc_word_active'):1
				if(this.currentIndex>-1){
					const li = this.$refs.lrcList.children[this.currentIndex]
					li.classList.add('lrc_word_active')
				}
			},
			findCurrentIndex() {
				const currentTime = this.$refs.myAudio.currentTime
				for (let index in this.lrcArr) {
					const lrc = this.lrcArr[index]
					if (lrc.time > currentTime) {
						this.currentIndex = index - 1
						return;
					}
				}
				this.currentIndex = this.lrcArr.length-1
			}
		}
	}
</script>

<style lang="scss">
	li {
		list-style: none;
	}

	body {
		background-color: #000000;
		text-align: center;
	}

	audio {
		width: 60%;
		padding: 20px 0px;
	}

	.lrc_box {
		height: calc(100vh - 120px);
		overflow: hidden;

		.lrc_list {
			transition: all 0.5s;

			.lrc_word {
				color: #666666;
				font-size: 18px;
				line-height: 30px;
				padding: 8px 0px;
			}

			.lrc_word_active {
				color: #FFFFFF;
				transform: scale(1.3);
				transition: all 0.3s;
			}
		}
	}
</style>